#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <vector>
#include "thread.hpp"

std::string Getthreadname()
{
    static int number = 1;
    char name[64];
    snprintf(name, sizeof(name), "Thread-%d", number++);
    return name;
}

void Print(int num)
{
    while (num)
    {
        std::cout << "hello world: " << num-- << std::endl;
        sleep(1);
    }
}

int Ticket = 1000;

void Getticket(pthread_mutex_t *lock)
{

    while(true)
    {
        pthread_mutex_lock(lock);
        if(Ticket > 0)
        {
            usleep(1000);//time for getticket
            Ticket--;
            printf("get a ticket : %d", Ticket);
            pthread_mutex_unlock(lock);
        }
        else{
            pthread_mutex_unlock(lock);
            break;
        }
    }
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, NULL);

    std::string name1 = Getthreadname();
    Thread<pthread_mutex_t*> t1(name1, Getticket, &mutex);

    std::string name2 = Getthreadname();
    Thread<pthread_mutex_t*> t2(name2, Getticket, &mutex);

    std::string name3 = Getthreadname();
    Thread<pthread_mutex_t*> t3(name3, Getticket, &mutex);

    std::string name4 = Getthreadname();
    Thread<pthread_mutex_t*> t4(name4, Getticket, &mutex);

    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();

    t1.Join();
    t2.Join();
    t3.Join();
    t4.Join();

    pthread_mutex_destroy(&mutex);

    return 0;
}